<!doctype html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <title>添加字幕 | TEFS</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
  <style>
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
      font-family: "Microsoft YaHei", Arial, sans-serif;
    }

    /* 视频背景容器 */
    .background-container {
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      z-index: -1;
      overflow: hidden;
      background-color: #000;
    }

    /* 背景视频样式 */
    .background-video {
      position: absolute;
      top: 50%;
      left: 50%;
      min-width: 100%;
      min-height: 100%;
      width: auto;
      height: auto;
      transform: translate(-50%, -50%);
      filter: brightness(0.6);
      opacity: 0;
      transition: opacity 0.5s ease-in-out;
    }

    .background-video.loaded {
      opacity: 1;
    }

    body {
      background-color: transparent;
      color: #333;
      position: relative;
      padding-bottom: 60px;
      transition: background-color 0.3s, color 0.3s;
      padding-top: 60px;
    }

    /* 深色模式样式 */
    body.dark-mode {
      background-color: #1a1a1a;
      color: #f0f0f0;
    }

    /* 顶部导航栏 */
    .top-nav {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 12px 20px;
      background: rgba(255, 255, 255, 0.9);
      box-shadow: 0 1px 2px rgba(0, 0, 0, 0.08);
      transition: background-color 0.3s;
      position: fixed;
      width: 100%;
      top: 0;
      z-index: 1000;
    }

    body.dark-mode .top-nav {
      background: rgba(30, 30, 30, 0.9);
    }

    .top-nav .logo {
      font-size: 18px;
      font-weight: bold;
      color: #333;
      transition: color 0.3s;
    }

    body.dark-mode .top-nav .logo {
      color: #f0f0f0;
    }

    .top-nav .user-area {
      display: flex;
      align-items: center;
      gap: 16px;
    }

    .top-nav .user-area span {
      color: #666;
      transition: color 0.3s;
    }

    body.dark-mode .top-nav .user-area span {
      color: #ccc;
    }

    .logout-btn, .profile-btn, .back-btn {
      padding: 6px 14px;
      color: #fff;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      transition: background-color 0.2s;
    }

    .back-btn {
      background-color: #50d8e0;
      margin-right: 10px;
    }

    body.dark-mode .back-btn {
      background-color: #40b8c0;
    }

    .profile-btn {
      background-color: #4a86e8;
      margin-right: 10px;
    }

    body.dark-mode .profile-btn {
      background-color: #3a66c8;
    }

    .profile-btn:hover {
      background-color: #3a76d8;
    }

    .logout-btn {
      background-color: #ff6347;
    }

    body.dark-mode .logout-btn {
      background-color: #e54a30;
    }

    .logout-btn:hover {
      background-color: #e55236;
    }

    /* 主容器 */
    .container {
      max-width: 1200px;
      margin: 30px auto;
      padding: 0 20px;
    }

    .page-title {
      font-size: 2rem;
      margin-bottom: 20px;
      color: white;
      text-shadow: 0 2px 4px rgba(0, 0, 0, 0.5);
      text-align: center;
    }

    .page-description {
      font-size: 1.1rem;
      margin-bottom: 30px;
      color: rgba(255, 255, 255, 0.9);
      text-align: center;
      max-width: 800px;
      margin-left: auto;
      margin-right: auto;
    }

    /* 表单区域 */
    .form-container {
      display: flex;
      flex-wrap: wrap;
      gap: 30px;
      margin-bottom: 40px;
    }

    .upload-section {
      flex: 1;
      min-width: 300px;
      background: rgba(255, 255, 255, 0.85);
      border-radius: 12px;
      padding: 25px;
      box-shadow: 0 6px 12px rgba(0, 0, 0, 0.15);
      display: flex;
      flex-direction: column;
      gap: 25px;
      transition: background-color 0.3s, box-shadow 0.3s;
    }

    body.dark-mode .upload-section {
      background: rgba(40, 40, 40, 0.85);
      box-shadow: 0 6px 12px rgba(0, 0, 0, 0.3);
    }

    /* 调整设置区域样式 */
    .settings-section {
      flex: 1;
      min-width: 300px;
      background: rgba(255, 255, 255, 0.85);
      border-radius: 12px;
      padding: 25px;
      box-shadow: 0 6px 12px rgba(0, 0, 0, 0.15);
      transition: background-color 0.3s, box-shadow 0.3s;
      min-height: 600px;
      display: flex;
      flex-direction: column;
    }

    body.dark-mode .settings-section {
      background: rgba(40, 40, 40, 0.85);
      box-shadow: 0 6px 12px rgba(0, 0, 0, 0.3);
    }

    .section-title {
      font-size: 1.4rem;
      margin-bottom: 20px;
      color: #333;
      padding-bottom: 10px;
      border-bottom: 2px solid #4a86e8;
      transition: color 0.3s;
    }

    body.dark-mode .section-title {
      color: #f0f0f0;
    }

    /* 文件上传区域 */
    .upload-area {
      border: 2px dashed #ccc;
      border-radius: 8px;
      padding: 30px 20px;
      text-align: center;
      cursor: pointer;
      transition: all 0.3s;
      margin-bottom: 0;
      background-color: #f9f9f9;
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: center;
    }

    body.dark-mode .upload-area {
      border-color: #555;
      background-color: #2a2a2a;
    }

    .upload-area:hover {
      border-color: #4a86e8;
      background-color: #f0f7ff;
    }

    body.dark-mode .upload-area:hover {
      background-color: #3a3a4a;
    }

    .upload-icon {
      font-size: 48px;
      color: #4a86e8;
      margin-bottom: 15px;
    }

    .upload-text {
      font-size: 1rem;
      color: #666;
      margin-bottom: 15px;
      transition: color 0.3s;
    }

    body.dark-mode .upload-text {
      color: #ccc;
    }

    .upload-btn {
      padding: 8px 20px;
      background-color: #4a86e8;
      color: white;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      transition: background-color 0.2s;
    }

    .upload-btn:hover {
      background-color: #3a76d8;
    }

    .file-info {
      margin-top: 15px;
      font-size: 0.9rem;
      color: #666;
      transition: color 0.3s;
    }

    body.dark-mode .file-info {
      color: #ccc;
    }

    .file-name {
      font-weight: bold;
      color: #333;
      transition: color 0.3s;
    }

    body.dark-mode .file-name {
      color: #ddd;
    }

    /* 设置表单样式 */
    .form-group {
      margin-bottom: 20px;
      padding: 10px;
      background-color: #f9f9f9;
      border-radius: 6px;
      transition: background-color 0.3s;
    }

    body.dark-mode .form-group {
      background-color: #2a2a2a;
    }

    .form-label {
      display: block;
      margin-bottom: 8px;
      font-weight: bold;
      color: #333;
      transition: color 0.3s;
    }

    body.dark-mode .form-label {
      color: #f0f0f0;
    }

    .form-label .value-display {
      color: #666;
      font-weight: normal;
      margin-left: 8px;
      transition: color 0.3s;
    }

    body.dark-mode .form-label .value-display {
      color: #ccc;
    }

    .form-input {
      width: 100%;
      padding: 10px;
      border: 1px solid #ddd;
      border-radius: 4px;
      font-size: 1rem;
      background-color: #fff;
      color: #333;
      transition: background-color 0.3s, border-color 0.3s, color 0.3s;
    }

    body.dark-mode .form-input {
      background-color: #3a3a3a;
      border-color: #555;
      color: #f0f0f0;
    }

    .color-picker {
      display: flex;
      align-items: center;
      gap: 10px;
    }

    .color-input {
      width: 50px;
      height: 30px;
      border: none;
      cursor: pointer;
    }

    /* 颜色设置组合样式 */
    .color-settings-container {
      display: flex;
      gap: 15px;
      flex-wrap: wrap;
    }

    .color-settings .color-picker {
      flex: 1;
      min-width: 150px;
    }

    .position-selector {
      display: flex;
      gap: 15px;
      margin-top: 5px;
    }

    .position-btn {
      flex: 1;
      padding: 10px;
      background: #f0f0f0;
      border: 1px solid #ddd;
      border-radius: 4px;
      cursor: pointer;
      text-align: center;
      transition: all 0.2s;
      color: #333;
    }

    body.dark-mode .position-btn {
      background: #3a3a3a;
      border-color: #555;
      color: #ccc;
    }

    .position-btn.active,
    body.dark-mode .position-btn.active {
      background: #4a86e8;
      color: white;
      border-color: #3a76d8;
    }

    .submit-btn {
      width: 300px;
      padding: 12px;
      background-color: #28a745;
      color: white;
      border: none;
      border-radius: 4px;
      font-size: 1.1rem;
      cursor: pointer;
      transition: background-color 0.2s;
      margin: 20px auto 40px;
      display: block;
    }

    body.dark-mode .submit-btn {
      background-color: #218838;
    }

    .submit-btn:hover {
      background-color: #218838;
    }

    body.dark-mode .submit-btn:hover {
      background-color: #1d7830;
    }

    .submit-btn:disabled {
      background-color: #cccccc;
      cursor: not-allowed;
    }

    /* 任务列表区域 */
    .tasks-container {
      background: rgba(255, 255, 255, 0.85);
      border-radius: 12px;
      padding: 25px;
      box-shadow: 0 6px 12px rgba(0, 0, 0, 0.15);
      transition: background-color 0.3s, box-shadow 0.3s;
    }

    body.dark-mode .tasks-container {
      background: rgba(40, 40, 40, 0.85);
      box-shadow: 0 6px 12px rgba(0, 0, 0, 0.3);
    }

    .tasks-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
    }

    .tasks-title {
      font-size: 1.4rem;
      color: #333;
      transition: color 0.3s;
    }

    body.dark-mode .tasks-title {
      color: #f0f0f0;
    }

    .refresh-btn {
      padding: 8px 15px;
      background-color: #4a86e8;
      color: white;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      transition: background-color 0.2s;
    }

    body.dark-mode .refresh-btn {
      background-color: #3a66c8;
    }

    .refresh-btn:hover {
      background-color: #3a76d8;
    }

    .tasks-list {
      max-height: 400px;
      overflow-y: auto;
    }

    .task-item {
      padding: 15px;
      border-bottom: 1px solid #eee;
      display: flex;
      justify-content: space-between;
      align-items: center;
      transition: border-color 0.3s;
    }

    body.dark-mode .task-item {
      border-bottom: 1px solid #444;
    }

    .task-item:last-child {
      border-bottom: none;
    }

    .task-info {
      flex: 1;
    }

    .task-name {
      font-weight: bold;
      color: #333;
      margin-bottom: 5px;
      transition: color 0.3s;
    }

    body.dark-mode .task-name {
      color: #f0f0f0;
    }

    .task-meta {
      font-size: 0.9rem;
      color: #666;
      transition: color 0.3s;
    }

    body.dark-mode .task-meta {
      color: #ccc;
    }

    .task-status {
      padding: 5px 10px;
      border-radius: 4px;
      font-size: 0.9rem;
      font-weight: bold;
    }

    .status-processing {
      background-color: #ffc107;
      color: #333;
    }

    .status-completed {
      background-color: #28a745;
      color: white;
    }

    .status-failed {
      background-color: #dc3545;
      color: white;
    }

    .task-actions .download-btn {
      padding: 6px 12px;
      background-color: #4a86e8;
      color: white;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      transition: background-color 0.2s;
      margin-left: 10px;
    }

    body.dark-mode .task-actions .download-btn {
      background-color: #3a66c8;
    }

    .task-actions .download-btn:hover {
      background-color: #3a76d8;
    }

    /* 预览区域样式 */
    .preview-container {
      position: relative;
      height: 300px;
      min-height: 300px;
      background-color: #ffffff;
      border-radius: 4px;
      overflow: hidden;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-top: 20px;
      transition: background-color 0.3s;
      flex-shrink: 0;
      z-index: 10;
    }

    .preview-background {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background-size: cover;
      background-position: center;
      z-index: 0;
      background-image: url("/static/images/R-C.jpg");
    }

    .subtitle-preview {
      padding: 8px 16px;
      border-radius: 4px;
      font-size: 24px;
      color: #FFFFFF;
      background-color: rgba(0, 0, 0, 0.7);
      position: relative;
      z-index: 1;
    }

    body.dark-mode .preview-background {
      /* 深色模式下的背景图效果 */
    }

    body.dark-mode .preview-container {
      background-color: #1a1a1a;
    }

    /* 滑块样式 */
    input[type="range"] {
      -webkit-appearance: none;
      width: 100%;
      height: 8px;
      border-radius: 4px;
      background: #ddd;
      outline: none;
      margin: 10px 0;
      padding: 0;
      transition: background 0.3s;
    }

    body.dark-mode input[type="range"] {
      background: #555;
    }

    input[type="range"]::-webkit-slider-thumb {
      -webkit-appearance: none;
      width: 20px;
      height: 20px;
      border-radius: 50%;
      background: #4a86e8;
      cursor: pointer;
      border: none;
    }

    input[type="range"]::-moz-range-thumb {
      width: 20px;
      height: 20px;
      border-radius: 50%;
      background: #4a86e8;
      cursor: pointer;
      border: none;
    }

    /* 底部固定黑框 */
    .footer {
      position: fixed;
      bottom: 0;
      left: 0;
      width: 100%;
      background: rgba(51, 51, 51, 0.9);
      color: #fff;
      text-align: center;
      padding: 12px 0;
      font-size: 12px;
      transition: background-color 0.3s;
      z-index: 20;
    }




    body.dark-mode .footer {
      background: rgba(20, 20, 20, 0.9);
    }
  </style>
</head>

<body>
  <!-- 视频背景容器 -->
  <div class="background-container">
    <video class="background-video" autoplay muted loop playsinline>
      <source src="/static/videos/c1.mp4" type="video/mp4">
      <source src="/static/videos/background.webm" type="video/webm">
      您的浏览器不支持视频背景
    </video>
  </div>

  <!-- 顶部导航 -->
  <div class="top-nav">
    <div class="logo">TEFS</div>
    <div class="user-area">
        <a href="{{ url_for('features') }}">
            <button class="back-btn">返回功能页</button>
        </a>
        <span>用户</span>
        <span>{{ username }}</span>
        <a href="{{ url_for('profile') }}">
            <button class="profile-btn">账户设置</button>
        </a>
        <a href="{{ url_for('logout') }}">
            <button class="logout-btn">登出</button>
        </a>
        <button id="theme-toggle" style="margin-left: 10px; padding: 6px 12px; background-color: #4a86e8; color: white; border: none; border-radius: 4px; cursor: pointer;">切换深色模式</button>
    </div>
</div>

  <!-- 主容器 -->
  <div class="container">
    <h1 class="page-title">添加字幕到视频</h1>
    <p class="page-description">上传视频和字幕文件，自定义字幕样式并添加到视频中</p>

    <!-- 表单区域 -->
    <div class="form-container">
      <!-- 上传区域 -->
      <div class="upload-section">
        <h2 class="section-title">上传文件</h2>

        <div class="upload-area" id="video-upload-area">
          <i class="fas fa-video upload-icon"></i>
          <p class="upload-text">点击或拖放视频文件到此处</p>
          <button class="upload-btn">选择视频文件</button>
          <input type="file" id="video-file" accept="video/*" style="display: none;">
          <div class="file-info" id="video-file-info">未选择文件</div>
        </div>

        <div class="upload-area" id="subtitle-upload-area">
          <i class="fas fa-file-alt upload-icon"></i>
          <p class="upload-text">点击或拖放字幕文件到此处</p>
          <button class="upload-btn">选择字幕文件</button>
          <input type="file" id="subtitle-file" accept=".srt,.txt" style="display: none;">
          <div class="file-info" id="subtitle-file-info">未选择文件</div>
        </div>
      </div>

      <!-- 设置区域 -->
      <div class="settings-section">
        <h2 class="section-title">字幕设置</h2>

        <!-- 字体大小设置 -->
        <div class="form-group">
          <label class="form-label">
            字体大小：
            <span class="value-display" id="font-size-value">24px</span>
          </label>
          <input type="range" class="form-input slider-control" id="font-size" min="10" max="50" value="24">
        </div>

        <!-- 透明度设置 -->
        <div class="form-group">
          <label class="form-label">
            背景透明度：
            <span class="value-display" id="bg-opacity-value">0.7</span>
          </label>
          <input type="range" class="form-input slider-control" id="bg-opacity" min="0" max="10" value="7">
        </div>

        <!-- 颜色设置组合区域 -->
        <div class="form-group color-settings">
          <label class="form-label">颜色设置</label>
          <div class="color-settings-container">
            <!-- 字体颜色设置 -->
            <div class="color-picker">
              <input type="color" class="color-input" id="font-color" value="#FFFFFF">
              <span>字体颜色: </span>
              <span id="font-color-value">白色</span>
            </div>

            <!-- 背景颜色设置 -->
            <div class="color-picker">
              <input type="color" class="color-input" id="bg-color" value="#000000">
              <span>背景颜色: </span>
              <span id="bg-color-value">黑色</span>
            </div>
          </div>
        </div>

        <!-- 字幕位置设置 -->
        <div class="form-group">
          <label class="form-label">字幕位置</label>
          <div class="position-selector">
            <div class="position-btn active" data-position="bottom">底部</div>
            <div class="position-btn" data-position="middle">中部</div>
            <div class="position-btn" data-position="top">顶部</div>
          </div>
        </div>

        <!-- 字幕预览区域 -->
        <div class="preview-container">
          <div class="preview-background"></div>
          <div class="subtitle-preview">
            字幕预览
          </div>
        </div>
      </div>
    </div>

    <!-- 移到外部的提交按钮 -->
    <button class="submit-btn" id="submit-btn">开始添加字幕</button>
    <!-- 任务列表区域 -->
    <div class="tasks-container">
      <div class="tasks-header">
        <h2 class="tasks-title">字幕任务历史</h2>
        <button class="refresh-btn" id="refresh-btn">
          <i class="fas fa-sync-alt"></i> 刷新
        </button>
      </div>

      <div class="tasks-list" id="tasks-list">
        {% for task in subtitle_tasks %}
        <div class="task-item">
          <div class="task-info">
            <div class="task-name">{{ task.video_name }}</div>
            <div class="task-meta">
              创建时间: {{ task.created_at.strftime('%Y-%m-%d %H:%M') }} |
              字幕位置: {{ task.position }}
            </div>
          </div>
          <div class="task-status status-{{ task.status }}">
            {{ '处理中' if task.status == 'processing' else '已完成' if task.status == 'completed' else '失败' }}
          </div>
          <div class="task-actions">
            {% if task.status == 'completed' %}
            <button class="download-btn" data-task-id="{{ task.id }}">
              <i class="fas fa-download"></i> 下载
            </button>
            {% endif %}
          </div>
        </div>
        {% else %}
        <div class="task-item">
          <div class="task-info">
            暂无字幕任务记录
          </div>
        </div>
        {% endfor %}
      </div>
    </div>
  </div>

  <!-- 底部固定黑框 -->
  <div class="footer">
    产品由句号团队开发
  </div>

  <script>
    // 视频加载完成后显示
    document.addEventListener('DOMContentLoaded', function() {
      const backgroundVideo = document.querySelector('.background-video');
      backgroundVideo.classList.add('loaded');

      // 深色模式切换功能
      const themeToggle = document.getElementById('theme-toggle');
      const body = document.body;

      // 检查本地存储中的主题偏好
      if (localStorage.getItem('darkMode') === 'true') {
        body.classList.add('dark-mode');
        themeToggle.textContent = '切换浅色模式';
      }

      // 切换主题
      themeToggle.addEventListener('click', function() {
        body.classList.toggle('dark-mode');

        // 保存主题偏好到本地存储
        if (body.classList.contains('dark-mode')) {
          localStorage.setItem('darkMode', 'true');
          themeToggle.textContent = '切换浅色模式';
        } else {
          localStorage.setItem('darkMode', 'false');
          themeToggle.textContent = '切换深色模式';
        }
      });

      // 文件上传处理
      const videoUploadArea = document.getElementById('video-upload-area');
      const videoFileInput = document.getElementById('video-file');
      const videoFileInfo = document.getElementById('video-file-info');

      const subtitleUploadArea = document.getElementById('subtitle-upload-area');
      const subtitleFileInput = document.getElementById('subtitle-file');
      const subtitleFileInfo = document.getElementById('subtitle-file-info');

      // 视频上传
      videoUploadArea.addEventListener('click', () => videoFileInput.click());
      videoFileInput.addEventListener('change', function() {
        if (this.files.length > 0) {
          videoFileInfo.innerHTML = `已选择: <span class="file-name">${this.files[0].name}</span>`;
        }
      });

      // 字幕上传
      subtitleUploadArea.addEventListener('click', () => subtitleFileInput.click());
      subtitleFileInput.addEventListener('change', function() {
        if (this.files.length > 0) {
          subtitleFileInfo.innerHTML = `已选择: <span class="file-name">${this.files[0].name}</span>`;
        }
      });

      // 拖放功能
      [videoUploadArea, subtitleUploadArea].forEach(area => {
        area.addEventListener('dragover', (e) => {
          e.preventDefault();
          area.style.borderColor = '#4a86e8';
          area.style.backgroundColor = '#f0f7ff';
        });

        area.addEventListener('dragleave', () => {
          area.style.borderColor = '#ccc';
          area.style.backgroundColor = '#f9f9f9';
        });

        area.addEventListener('drop', (e) => {
          e.preventDefault();
          area.style.borderColor = '#ccc';
          area.style.backgroundColor = '#f9f9f9';

          const files = e.dataTransfer.files;
          if (files.length > 0) {
            const file = files[0];
            if (area.id === 'video-upload-area' && file.type.startsWith('video/')) {
              videoFileInput.files = files;
              videoFileInfo.innerHTML = `已选择: <span class="file-name">${file.name}</span>`;
            } else if (area.id === 'subtitle-upload-area' &&
                      (file.name.endsWith('.srt') || file.name.endsWith('.txt'))) {
              subtitleFileInput.files = files;
              subtitleFileInfo.innerHTML = `已选择: <span class="file-name">${file.name}</span>`;
            }
          }
        });
      });

      // 字幕设置
      // 字体大小滑块控制
      const fontSizeSlider = document.getElementById('font-size');
      const fontSizeValue = document.getElementById('font-size-value');

      fontSizeSlider.addEventListener('input', function() {
        fontSizeValue.textContent = `${this.value}px`;
      });

      // 字体颜色设置
      const fontColorPicker = document.getElementById('font-color');
      const fontColorValue = document.getElementById('font-color-value');

      fontColorPicker.addEventListener('input', function() {
        fontColorValue.textContent = this.value;
      });

      // 背景颜色设置
      const bgColorPicker = document.getElementById('bg-color');
      const bgColorValue = document.getElementById('bg-color-value');

      bgColorPicker.addEventListener('input', function() {
        bgColorValue.textContent = this.value;
      });

      // 透明度设置
      const bgOpacitySlider = document.getElementById('bg-opacity');
      const bgOpacityValue = document.getElementById('bg-opacity-value');

      bgOpacitySlider.addEventListener('input', function() {
        const opacity = this.value / 10;
        bgOpacityValue.textContent = opacity.toFixed(1);
      });

      // 位置选择
      const positionBtns = document.querySelectorAll('.position-btn');
      positionBtns.forEach(btn => {
        btn.addEventListener('click', function() {
          positionBtns.forEach(b => b.classList.remove('active'));
          this.classList.add('active');
        });
      });

      // 实时更新字幕预览
      function updatePreview() {
       const subtitlePreview = document.querySelector('.subtitle-preview');
       if (!subtitlePreview) return;

      // 获取当前设置值
      const fontSize = `${fontSizeSlider.value}px`;
      const fontColor = fontColorPicker.value;
      const bgColor = bgColorPicker.value;
      const bgOpacity = bgOpacitySlider.value / 10;
      const position = document.querySelector('.position-btn.active').dataset.position;

      // 更新预览样式
      subtitlePreview.style.fontSize = fontSize;
      subtitlePreview.style.color = fontColor;
      subtitlePreview.style.backgroundColor = `${bgColor}${Math.round(bgOpacity * 255).toString(16).padStart(2, '0')}`;

      // 获取预览容器
      const previewContainer = document.querySelector('.preview-container');

      // 清除之前的定位样式
      previewContainer.style.alignItems = 'center';
      previewContainer.style.justifyContent = 'center';
      subtitlePreview.style.position = 'relative';
      subtitlePreview.style.top = 'auto';
      subtitlePreview.style.bottom = 'auto';
      subtitlePreview.style.left = 'auto';
      subtitlePreview.style.transform = 'none';

      // 根据选择的位置调整
      if (position === 'top') {
        previewContainer.style.alignItems = 'flex-start';
      } else if (position === 'bottom') {
        previewContainer.style.alignItems = 'flex-end';
      }
      }

      // 为所有设置项添加事件监听，触发预览更新
      fontSizeSlider.addEventListener('input', updatePreview);
      fontColorPicker.addEventListener('input', updatePreview);
      bgColorPicker.addEventListener('input', updatePreview);
      bgOpacitySlider.addEventListener('input', updatePreview);
      positionBtns.forEach(btn => {
        btn.addEventListener('click', updatePreview);
      });

      // 初始化预览样式
      updatePreview();

            // 提交按钮
            // 提交按钮
      const submitBtn = document.getElementById('submit-btn');
      submitBtn.addEventListener('click', async function() {
        const videoFile = document.getElementById('video-file').files[0];
        const subtitleFile = document.getElementById('subtitle-file').files[0];

        if (!videoFile) {
          alert('请选择视频文件');
          return;
        }
        if (!subtitleFile) {
          alert('请选择字幕文件');
          return;
        }

        const fontSize = document.getElementById('font-size').value;
        const fontColor = document.getElementById('font-color').value;
        const bgColor = document.getElementById('bg-color').value;
        const bgOpacity = document.getElementById('bg-opacity').value / 10;
        const position = document.querySelector('.position-btn.active').dataset.position;

        const formData = new FormData();
        formData.append('video', videoFile);
        formData.append('subtitle', subtitleFile);
        formData.append('font_size', fontSize);
        formData.append('font_color', fontColor);
        formData.append('bg_color', bgColor);
        formData.append('bg_opacity', bgOpacity);
        formData.append('position', position);

        submitBtn.disabled = true;
        submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 提交中...';

        try {
            const response = await fetch("{{ url_for('add_subtitles') }}", {
                method: 'POST',
                body: formData
            });
            const result = await response.json();

            if (result.success) {
                submitBtn.disabled = false;
                submitBtn.innerHTML = '开始添加字幕';
              const videoFileName = videoFile.name;
              const tasksList = document.getElementById('tasks-list');
              const newProgressTaskHTML = `
                <div class="task-item" id="task-item-progress-${result.task_id}">
                  <div class="task-info">
                    <div class="task-name">${videoFileName}</div>
                    <div class="task-meta">
                      <!-- 限制了最大宽度的进度条容器 -->
                      <div style="background-color: #e9ecef; border-radius: .25rem; height: 20px; margin-top: 5px; overflow: hidden; max-width: 500px;">
                        <div id="progress-bar-${result.task_id}" style="width: 0%; height: 100%; background-color: #ffc107; border-radius: .25rem; transition: width 0.4s ease;"></div>
                      </div>
                    </div>
                  </div>
                  <div class="task-status status-processing">
                    <span id="progress-text-${result.task_id}" style="font-weight: bold;">0%</span>
                  </div>
                  <div class="task-actions">
                    <!-- No actions while processing -->
                  </div>
                </div>
              `;
              // Insert the new HTML at the top of the list
              tasksList.insertAdjacentHTML('afterbegin', newProgressTaskHTML);
              startProgressPolling(result.task_id);

            } else {
                alert('任务提交失败: ' + result.message);
                submitBtn.disabled = false;
                submitBtn.innerHTML = '开始添加字幕';
            }
        } catch (error) {
            alert('请求失败: ' + error.message);
            submitBtn.disabled = false;
            submitBtn.innerHTML = '开始添加字幕';
        }
    });
   function startProgressPolling(taskId) {
    // 获取DOM元素
    const progressBar = document.getElementById(`progress-bar-${taskId}`);
    const progressText = document.getElementById(`progress-text-${taskId}`);
    const taskItem = document.getElementById(`task-item-progress-${taskId}`);
    const statusElement = taskItem?.querySelector('.task-status');

    // 校验元素
    if (!progressBar || !progressText || !statusElement) return;

    // 配置参数（可根据需求调整）
    const STAGNATION_THRESHOLD = 3000; // 进度停滞判断时间（毫秒）
    const MIN_PROGRESS_FOR_COMPLETION = 50; // 允许自动完成的最小进度

    // 状态变量
    let state = {
        current: 0,
        completed: false,
        failed: false,
        timer: null,
        finalPushInterval: null,
        lastProgressTime: 0, // 最后一次次进度更新时间
        lastProgressValue: 0 // 上一次进度值
    };

    // 批量更新UI
    const updateUI = (progress, text, color) => {
        progressBar.style.width = `${progress}%`;
        progressBar.style.backgroundColor = color;
        progressText.textContent = text;
        statusElement.textContent = `处理中: ${text}`;
    };

    // 处理成功完成
    const handleSuccess = () => {
        if (state.completed || state.failed) return;

        // 清除所有定时器
        clearInterval(state.timer);
        if (state.finalPushInterval) clearInterval(state.finalPushInterval);

        // 强制设置为100%
        state.current = 100;
        progressBar.style.width = "100%";
        progressBar.style.backgroundColor = "#28a745";
        progressText.textContent = "100%";
        statusElement.textContent = "处理完成";

        state.completed = true;
        setTimeout(() => location.reload(), 1500);
    };

    // 处理失败
    const handleFailure = (msg) => {
        if (state.completed || state.failed) return;

        clearInterval(state.timer);
        if (state.finalPushInterval) clearInterval(state.finalPushInterval);

        progressBar.style.backgroundColor = "#dc2626";
        statusElement.textContent = `处理失败: ${msg}`;
        state.failed = true;
    };

    // 最终推进到100%
    const forceComplete = () => {
        if (state.finalPushInterval || state.completed || state.failed) return;

        // 平滑推进到100%
        let step = 1;
        state.finalPushInterval = setInterval(() => {
            state.current += step;

            // 加速最后阶段
            if (state.current > 95) step = 0.5;
            if (state.current > 98) step = 0.1;

            if (state.current >= 100) {
                state.current = 100;
                clearInterval(state.finalPushInterval);
                handleSuccess();
                return;
            }

            const displayText = `${state.current.toFixed(1)}%`;
            updateUI(state.current, displayText, "#28a745");
        }, 100);
    };

    // 轮询函数
    const checkProgress = async () => {
        if (state.completed || state.failed) return;

        try {
            const res = await fetch(`/task_progress/${taskId}`);
            if (!res.ok) throw new Error(`HTTP ${res.status}`);

            const data = await res.json();

            // 处理后端明确状态
            if (data.status === 'failed') {
                handleFailure(data.error || "未知错误");
                return;
            }
            if (data.status === 'completed') {
                handleSuccess();
                return;
            }

            // 计算进度（只增不减）
            const newProgress = Math.min(Math.max(0, parseFloat(data.progress) || 0), 100);

            // 检查进度是否有变化
            if (newProgress > state.current) {
                // 进度有更新，重置停滞计时器
                state.current = newProgress;
                state.lastProgressTime = Date.now();
                state.lastProgressValue = newProgress;

                const displayText = `${newProgress.toFixed(1)}%`;
                updateUI(newProgress, displayText, newProgress > 5 ? "#28a745" : "#ffc107");
            } else {
                // 进度无变化，检查是否已停滞
                const now = Date.now();
                const timeStagnated = now - state.lastProgressTime;

                // 如果进度停滞时间超过阈值，且已达到最低进度要求，则强制完成
                if (timeStagnated >= STAGNATION_THRESHOLD && state.current >= MIN_PROGRESS_FOR_COMPLETION) {
                    forceComplete();
                    return;
                }
            }

            // 正常完成判断
            if (state.current >= 100) {
                handleSuccess();
            }

        } catch (error) {
            handleFailure("连接错误");
        }
    };

    // 初始化
    state.lastProgressTime = Date.now();
    updateUI(0, "0%", "#ffc107");

    // 启动轮询
    state.timer = setInterval(checkProgress, 1000);
    checkProgress();

    // 超时保护
    setTimeout(() => {
        if (!state.completed && !state.failed) {
            handleFailure("超时");
        }
    }, 30 * 60 * 1000);
}



      // 刷新按钮
      const refreshBtn = document.getElementById('refresh-btn');
      refreshBtn.addEventListener('click', function() {
        location.reload();
      });

      // 下载按钮
      document.querySelectorAll('.download-btn').forEach(btn => {
        btn.addEventListener('click', function() {
          const taskId = this.getAttribute('data-task-id');
          window.location.href = `/download_subtitle/${taskId}`;
        });
      });
    });
  </script>
</body>
</html>